# backend/app/api/api_number.py

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app.db.db_handler import get_db
from app.db.db_models import Number, User
from app.auth.jwt import get_current_active_user
from app.db.db_number import DBNumber
from app.api.api_model import SuccessResponse

router = APIRouter(
    prefix="/number",
    tags=["Number Operations"],
)

db_dict = dict()

@router.get("/check", summary="检查最新数字")
async def get_check_number():
    """获取最新的数字"""
    db_number = db_dict["db_number"]
    number = db_number.get_latest_number()
    return SuccessResponse(data={"check_number": number.value if number else None})

@router.put("/update", summary="更新数字")
async def update_check_number(
    number: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """更新数字"""
    db_number = DBNumber(db)
    new_number = db_number.add_number(value=number, user_id=current_user.id)
    return SuccessResponse(data={"check_number": new_number.value})

@router.post("/post", summary="发送数字（需要认证）")
async def post_check_number(
    number: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """接收并存储数字"""
    if number <= 0:
        raise HTTPException(status_code=400, detail="数字必须大于0")
    db_number = DBNumber(db)
    new_number = db_number.add_number(value=number, user_id=current_user.id)
    return SuccessResponse(data={"check_number": new_number.value}) 

@router.post("/postWithoutAuth", summary="发送数字（无需认证）")
async def post_check_number_without_auth(
    number: int,
    db: Session = Depends(get_db)
):
    """接收并存储无需认证的数字"""
    if number <= 0:
        raise HTTPException(status_code=400, detail="数字必须大于0")
    db_number = DBNumber(db)
    new_number = db_number.add_number(value=number, user_id=None)  # 假设用户ID为None
    return SuccessResponse(data={"check_number": new_number.value})